import React, { Component } from "react"
import { connect } from 'react-redux'
import Template from "components/UI/template"
import { AdvancedTable } from "components/index"
import Selector from "components/selector"
import { messages, queryCurrencyPrecision } from "share/common"
import Department from "components/template/department"
import selectorData from "share/selectorData"
import moment from 'moment'
import NumberRange from "../expense-view/component/number-range"
import { Select, Popover, Row, Col, Button, message } from 'antd'
import httpFetch from "share/httpFetch"
import WrapFormItem from "components/wrap-form-item"
import DataHoc from "../../pay/template/data-hoc"
import Space from "components/space"
import AmortizationEdit from "./amortization-edit"
import EditSelect from "../../pay/template/edit-select"
import EditDate from "../../pay/template/edit-date"
import AmortizationHistory from "./amortization-history"
import menuRoute from "routes/menuRoute"
import chooserData from "share/chooserData"
import accurateFloat from 'containers/expense-report/template/accurate-float'

const { Middle } = Template;
const { Option } = Select;

@connect(mapStateToProps)
@DataHoc
class AmortizationManagement extends Component {

  service = (page, size, searchParams) => {
    return httpFetch.post(`/api/expense/amortization/finance/query`, {
      ...searchParams, page, size
    })
  };

  statusMap = [
    { key: '1001', label: messages('finance-8.key13')/*未摊销*/ },
    { key: '1003', label: messages('finance-8.key14')/*已摊销*/ }
  ];

  state = {
    setOfBooksId: this.props.company.setOfBooksId,
    rowSelection: this.props.getSelection()(),
    selectedData: [],
    loading: false,
    editCellError: false
  };

  searchForm = setOfBooksId => ([
    {
      component: isTitle => <Selector
        allowClear={false}
        type={'setOfBooksByTenant'}
        params={{ roleType: 'TENANT' }}
        entity
        onChange={value => this.handleChangeSetOfBook(value, isTitle)}
      />,
      id: 'setOfBooksId',
      judgeInTitle: true,
      label: messages('finance-8.key15')/*账套*/,
      initialValue: {
        setOfBooksName: this.props.company.setOfBooksName,
        id: setOfBooksId
      },
      tagUnclosed: true,
      parser: value => ({ setOfBooksId: value ? value.id : undefined }),
      tagParser: value => value.setOfBooksName
    },
    {
      id: 'companyOid', label: messages('finance-8.key16')/*付款公司*/, component: 'Chooser',
      props: {
        type: 'permission_company',
        labelKey: 'name',
        valueKey: 'companyOID',
        single: true,
        listExtraParams: { enabled: true, setOfBooksId: setOfBooksId }
      },
      parser: value => ({ companyOid: value ? value[0].companyOID : undefined })
    },
    {
      id: 'departmentOid', label: messages('common.department')/*部门*/, component: <Department single/>,
      parser: value => ({ departmentOid: value ? value[0].departmentOID : undefined }),
      tagParser: value => (value.map(item => item.title).join(','))
    },
    {
      id: 'applicantOid', label: messages('common.applicant')/*申请人*/, component: 'Selector',
      props: {
        placeholder: messages('common.please.enter')/*请输入*/ + messages('finance-8.key17')/*申请人姓名/工号*/,
        selectorItem: {
          ...selectorData['user'],
          key: 'userOID',
          label: record => (`${record.employeeID}-${record.fullName}${(record.status !== 1001 ?
              (`（${record.status === 1002 ?
                  messages('finance-8.key18')/*待离职员工*/ :
                  messages('finance-8.key19')/*离职员工*/}）`
              ) :
              ''
          )}`)
        },
        searchIfKeywordIsNull: true
      }
    },
    {
      id: 'financeApprovalDate', label: messages('finance-8.key20')/*审核日期*/, component: 'DateRangePicker',
      parser: value => ({
        financeApprovalDateFrom: value && value[0] ? moment(value[0]).format('YYYY-MM-DD') : null,
        financeApprovalDateTo: value && value[1] ? moment(value[1]).format('YYYY-MM-DD') : null
      })
    },
    {
      id: 'bookDate', label: messages('finance-8.key21')/*记账日期*/, component: 'DateRangePicker',
      parser: value => ({
        bookDateFrom: value && value[0] ? moment(value[0]).format('YYYY-MM-DD 00:00:00') : null,
        bookDateTo: value && value[1] ? moment(value[1]).format('YYYY-MM-DD 23:59:59') : null
      })
    },
    {
      id: 'periodSetCode',
      label: messages('finance-8.key5')/*摊销期间*/,
      component: (
        <WrapFormItem>
          {(onChange, value) => (
            <Row gutter={10}>
              <Col span={12}>
                <Selector
                  type='period_set'
                  entity={true}
                  searchIfKeywordIsNull
                  value={value.periodSetCodeFrom}
                  onChange={innerValue => onChange({
                    periodSetCodeFrom: innerValue,
                    periodSetCodeTo: undefined
                  })}
                  params={{ setOfBooksId: setOfBooksId }}
                />
              </Col>
              <Col span={12}>
                <Selector
                  type='period_set'
                  entity={true}
                  params={{ setOfBooksId: setOfBooksId, StartPeriod: (value.periodSetCodeFrom || {}).periodSeq }}
                  searchIfKeywordIsNull
                  disabled={!((value || {}).periodSetCodeFrom)}
                  value={value.periodSetCodeTo}
                  onChange={innerValue => onChange({ periodSetCodeTo: innerValue })}
                />
              </Col>
            </Row>
          )}
        </WrapFormItem>
      ),
      hasValue: value => value && value.periodSetCodeFrom,
      parser: value => value && value.periodSetCodeFrom ? {
        periodSetCodeFrom: value.periodSetCodeFrom.periodSeq,
        periodSetCodeTo: value.periodSetCodeTo ? value.periodSetCodeTo.periodSeq : undefined
      } : undefined,
      tagParser: value => `${value.periodSetCodeFrom.periodName}${value.periodSetCodeTo ? ' - ' + value.periodSetCodeTo.periodName : ''}`
    },
    {
      id: 'businessCode', component: 'Selector', label: messages('finance-8.key22')/*报销单号*/,
      props: {
        placeholder: messages('common.please.enter')/*请输入*/ + messages('common.document.code')/*单号*/,
        type: 'business_code_expense'
      }
    },
    {
      id: 'expenseTypeId', label: messages('common.expense.type')/*费用类型*/, component: 'Chooser',
      props: {
        selectorItem: Object.assign(chooserData['available_expense_type'], {
          searchForm: [{
            type: 'select',
            id: 'categoryId',
            colSpan: 12,
            label: messages('finance-8.key23')/*费用大类*/,
            options: [],
            getUrl: '/invoice/api/expense/types/groupby/category',
            labelKey: 'name',
            valueKey: 'id',
            method: 'get',
            getOptions: (item) => item.rows,
            renderOption: (data) => `${data.name}`
          }, {
            type: 'input',
            id: 'expenseTypeName',
            colSpan: 12,
            label: messages('finance-8.key24')/*费用名称*/
          }, {
            type: 'input',
            id: 'expenseTypeCode',
            colSpan: 12,
            label: messages('finance-8.key25')/*费用编码*/
          }]
        }),
        listExtraParams: { setOfBooksId: setOfBooksId },
        labelKey: 'name',
        valueKey: 'id',
        single: true
      },
      parser: value => ({ expenseTypeId: value ? value[0].id : undefined })
    },
    {
      id: 'baseAmount',
      label: messages('finance-8.key26')/*金额范围*/,
      component: <NumberRange/>,
      parser: value => ({
        baseAmountFrom: value && value[0] ? value[0] : null,
        baseAmountTo: value && value[1] ? value[1] : null
      }),
      tagParser: value => value && (value[0] || value[1]) && `${value[0] === 0 ? value[0] : value[0] || ''} ~ ${value[1] === 0 ? value[1] : value[1] || ''}`
    },
    {
      id: 'status', label: messages('finance-8.key27')/*摊销状态*/, component: 'Select',
      children: this.statusMap.map(item => <Option key={item.key}>{item.label}</Option>),
      props: {
        style: { width: '100%' },
        placeholder: messages('common.please.select')/*请选择*/
      },
      tagParser: value => (this.statusMap.find(item => item.key === value) || {}).label
    }
  ]);

  handleTabTitle = () => {
    const { selectedData } = this.state;
    let selectMap = selectedData.reduce((current, item) => {
      if (item.status === 1001) {
        if (current[item.baseCurrencyCode]) {
          current[item.baseCurrencyCode].amount += item.baseAmount;
          current[item.baseCurrencyCode].total += 1;
        } else {
          current[item.baseCurrencyCode] = {
            amount: item.baseAmount,
            total: 1
          }
        }
      }
      return current
    }, {});
    let unchecked = Object.keys(selectMap);
    let result = (
      <div>
        {messages('finance-8.key13')/*未摊销*/}
        <span className="ant-divider"/>
        {unchecked.map((item, index) => (
          <span>
            {messages('finance-8.key28',{arg1: item})/*金额：{arg1}*/}
            <span className="num-style">{this.filterMoney(selectMap[item].amount, queryCurrencyPrecision(item), true)}</span>
            <span className="ant-divider"/>
            {messages('finance-8.key29')/*交易笔数：*/}
            <span className="num-style">{selectMap[item].total}{messages('finance-8.key30')/*笔*/}</span>
            {index !== unchecked.length - 1 && <span className="ant-divider"/>}
          </span>
        ))}
      </div>
    );
    return selectedData.length > 0 ? result : undefined
  };

  handleChangeSetOfBook = (value, isTitle) => {
    const { setOfBooksId } = this.state;
    if (setOfBooksId !== value.id) {
      if (!isTitle) {
        this.advancedTableRef.advancedSearchRef.props.form.setFieldsValue({
          companyOid: undefined,
          periodSetCode: undefined,
          expenseTypeId: undefined
        });
      }
      this.setState({ setOfBooksId: value.id });
    }
  };

  columns = (setOfBooksId, editCellError) => ([
    {
      dataIndex: 'businessCode', title: messages('finance-8.key22')/*报销单号*/,
      render: (value, record) => <a onClick={() => this.openBusiness(record)}>{value}</a>
    },
    {
      dataIndex: 'financeApprovalDate', title: messages('finance-8.key20')/*审核日期*/,
      render: value => value ? moment(value).format('YYYY-MM-DD') : '-'
    },
    { dataIndex: 'companyName', title: messages('finance-8.key31')/*单据公司*/, hide: true },
    { dataIndex: 'applicantName', title: messages('common.applicant')/*申请人*/, hide: true },
    { dataIndex: 'formName', title: messages('common.document.name')/*单据名称*/, hide: true },
    { dataIndex: 'expenseTypeName', title: messages('common.expense.type')/*费用类型*/, hide: true },
    {
      dataIndex: 'title', title: messages('common.matter')/*事由说明temp*/, hide: true,
      render: value => <Popover content={value}>{value}</Popover>
    },
    { dataIndex: 'departmentName', title: messages('common.department')/*部门*/, hide: true },
    {
      dataIndex: 'costCenterItems', title: messages('finance-8.key1')/*成本中心*/, hide: true,
      render: value => JSON.parse(value).map(item => item.costCenterItemName).join(',')
    },
    { dataIndex: 'baseCurrencyCode', title: messages('finance-8.key2')/*本币币种*/ },
    {
      dataIndex: 'baseAmount', title: messages('finance-8.key3')/*摊销金额*/,
      render: (value, record) => this.filterMoney(value, queryCurrencyPrecision(record.baseCurrencyCode))
    },
    {
      dataIndex: 'amortizationRate', title: messages('finance-8.key32')/*每期摊销比例*/,
      render: value => accurateFloat.multiply(value, 100) + '%'
    },
    { dataIndex: 'relevantPersonName', title: messages('finance-8.key33')/*相关人*/, hide: true },
    {
      dataIndex: 'periodSetCode', title: messages('finance-8.key5')/*摊销期间*/,
      render: (value, record) => record.status === 1001 ? (
        <EditSelect
          url={`/api/periods/query/open/v2?setOfBooksId=${setOfBooksId}`}
          valueKey='periodName'
          label='periodName'
          value={{
            key: value,
            label: value
          }}
          onChange={value => this.handleEditRecord(value, record , 'periodSetCode')}
          onChangeError={editCellError}
        />
      ) : value
    },
    {
      dataIndex: 'bookDate', title: messages('finance-8.key21')/*记账日期*/, hide: true,
      render: (value, record) => record.status === 1001 ? (
        <EditDate
          value={value ? moment(value) : undefined}
          onChange={value => this.handleEditRecord(value, record , 'bookDate')}
          title={messages('finance-8.key34')/*默认执行摊销日期*/}
        />
      ) : (value ? moment(value).format('YYYY-MM-DD') : messages('finance-8.key34')/*默认执行摊销日期*/)
    },
    {
      dataIndex: 'status', title: messages('finance-8.key27')/*摊销状态*/,
      render: value => this.statusMap.find(item => item.key === (value + '')).label
    },
    {
      dataIndex: 'operator', title: messages('common.operation')/*操作*/,
      render: (value, record) => (
        <div>
          {
            record.status === 1001 && (
              <span>
                <a onClick={() => this.handleAmortization(false, record)}>{messages('finance-8.key35')/*执行摊销*/}</a>
                <span className="ant-divider"/>
                <a onClick={() => this.handleEdit(record)}>{messages('common.update')/*修改*/}</a>
                <span className="ant-divider"/>
              </span>
            )
          }
          <a onClick={() => this.handleViewHistory(record)}>{messages('finance-8.key12')/*摊销历史*/}</a>
        </div>
      )
    }
  ]);

  openBusiness = record => {
    window.open(
      menuRoute.getRouteItem('expense-report-detail-amortization', 'key').url
        .replace(':expenseReportOID', record.expenseReportOid)
        .replace(':pageFrom', 'amortization')
    );
  };

  handleAmortization = (isBatch = false, record) => {
    const { selectedData } = this.state;
    let params = isBatch ?
      selectedData
        .filter(item => item.status === 1001)
        .filter(item => item.expenseAmortizationId)
      : [record.expenseAmortizationId];
    this.setState({ loading: true });
    if (params.length) {
      httpFetch.post(`/api/expense/amortization/finance/amortization`, params).then(() => {
        message.success(messages('common.operate.success')/*操作成功*/);
        this.advancedTableRef.getList();
        this.props.onClearSelected();
      }).catch(e => {
        message.error(e.response.data.message);
      }).finally(() => {
        this.setState({ loading: false });
      })
    } else {
      message.error(messages('common.select')/*请选择temp*/)
    }
  };

  handleEdit = record => {
    AmortizationEdit.open(this, {
      record
    }).then(({data, closeModal, context}) => {
      return httpFetch.post(`/api/expense/amortization/finance/amortization/edit`, data).then(() => {
        this.advancedTableRef.getList();
      }).catch(e => {
        message.error(e.response.data.message);
      }).finally(() => {
        context.setState({ confirmLoading: false });
        closeModal();
      })
    })
  };

  handleEditRecord = (value, record, type) => {
    this.setState({ loading: true });
    httpFetch.post(`/api/expense/amortization/finance/amortization/edit`, [{
      ...record,
      [type]: value,
      operationType: 1002
    }]).then(() => {
      this.advancedTableRef.getList();
      this.setState({ editCellError: false });
    }).catch(e => {
      message.error(e.response.data.message);
      this.setState({ editCellError: true });
    }).finally(() => {
      this.setState({ loading: false });
    })
  };

  handleViewHistory = record => {
    AmortizationHistory.open(this, {
      expenseAmortizationId: record.expenseAmortizationId
    });
  };

  getSearchFrom = this.searchForm.memoize();

  getColumns = this.columns.memoize();

  render() {
    const { setOfBooksId, rowSelection, loading, editCellError, selectedData } = this.state;
    return (
      <Template>
        <Middle>
          <AdvancedTable
            title={messages('finance-8.key36')/*摊销管理*/}
            tableName='amortization-management'
            service={this.service}
            tableTitle={() => this.handleTabTitle()}
            onRef={ref => this.advancedTableRef = ref}
            searchForm={this.getSearchFrom(setOfBooksId)}
            columns={this.getColumns(setOfBooksId, editCellError)}
            rowKey="expenseAmortizationId"
            propsLoading={loading}
            rowClassName={record => record.status === 1003 ? 'row-select-display-none' : ''}
            rowSelection={rowSelection}
            footer={(
              <Space>
                <Button onClick={() => this.handleAmortization(true)} type={'primary'}>
                  {messages('finance-8.key35')/*执行摊销*/}
                </Button>
              </Space>
            )}
            filterLength={selectedData.filter(item => item.status === 1001).length}
          />
        </Middle>
      </Template>
    )
  }

}

function mapStateToProps(state) {
  return {
    company: state.login.company
  }
}

export default AmortizationManagement
